from pyecharts.charts import Bar,Timeline
from pyecharts.options import LabelOpts,TitleOpts
from pyecharts.globals import ThemeType
f=open("C:/Users/ASUS/Desktop/python/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv","r",encoding="GB2312")
data_line=f.readlines()
f.close()
#时间线
#设置主题也在这
timeline=Timeline({"theme":ThemeType.PURPLE_PASSION})
#删除第一行
data_line.pop(0)
#建立一个空列表
data_dict={}
for line in data_line:
    year=int(line.split(",")[0])
    country=line.split(",")[1]
    gdp=float(line.split(",")[2])#科学计数法转正常数字
    try:
        data_dict[year].append([country,gdp])
    except KeyError:
        data_dict[year]=[]
        data_dict[year].append([country,gdp])
#print(data_dict)
sorted_year_list=sorted(data_dict.keys())
for year in sorted_year_list:
    data_dict[year].sort(key=lambda element:element[1],reverse=True)
    #取出本年分前八的国家
    year_data=data_dict[year][0:8]
    x_data=[]
    y_data=[]
    for country_gdp in year_data:
        x_data.append(country_gdp[0])#x国家
        y_data.append(country_gdp[1]/100000000)#yGDp
    # 构建柱状图
    bar = Bar()
    y_data.reverse()
    x_data.reverse()
    bar.add_xaxis(x_data)
    bar.add_yaxis("GDP(亿）", y_data, label_opts=LabelOpts(position="right"))
    # 反转x轴和y轴
    bar.reversal_axis()
    timeline.add(bar,str(year))
    #设置标题
    bar.set_global_opts(
        title_opts=TitleOpts(title=f"{year}年全球前八GDP国家")
    )
#设置时间线自动播放
timeline.add_schema(
    play_interval=1000,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=True
)
#绘图
timeline.render("1960-2019全求GDP前八国家.html")

